package me.chinaq.fastweb.controller;

import me.chinaq.fastweb.ProjectConstant;
import me.chinaq.fastweb.web.ApiResult;
import me.chinaq.fastweb.web.CounterHandler;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * Created by shaoqi on 7/6/2017.
 */
@RestController
@RequestMapping
public class IndexController {
	@Autowired(required = false)
	CounterHandler counterHandler;
	@Autowired(required = false)
	private SimpMessagingTemplate simpMessagingTemplate;

	@GetMapping("contB")
	public String contB() {
		System.out.println(System.currentTimeMillis());
		return ProjectConstant.b;
	}

	@GetMapping("contC")
	public int contC() {
		return ProjectConstant.C;
	}

	@GetMapping("contD")
	public String contD() {
		return ProjectConstant.D;
	}


	@GetMapping
	public String index() {
		return "hello";
	}

	@GetMapping("xss")
	public String xss(String xss) {
		return xss;
	}

	@RequestMapping("xssJson")
	public Map<String, Object> xss(@RequestBody Map<String, Object> xss) {
		return xss;
	}

	@GetMapping("poll")
	public int poll() {
		int nextInt = RandomUtils.nextInt(1, 10);
		try {
			Thread.sleep(nextInt * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return nextInt;
	}

	@GetMapping("count")
	public String count(String count) {
		counterHandler.sendMessageToUser(count, "当前时间是：" + new Date().toLocaleString());
		return "已发送";
	}

	@GetMapping("notice")
	public String notice(String count) {
		//counterHandler.sendMessageToUser(count, "当前时间是：" + new Date().toLocaleString());
		simpMessagingTemplate.convertAndSendToUser(count, "/queue/notice", "当前时间是：" + new Date());
		return "已发送";
	}

	/**
	 * 应用场景为：请求-响应模式
	 * 客户端订阅某一个目的地，然后预期在这个目的地上获得一个一次性的响应(异步)
	 *
	 * @return
	 */
	@SubscribeMapping("/subscribe/hello")
	public ApiResult<String> handlerSubscribe(String name) {
		System.out.println("===============================name");
		String message = String.format("welcome！you have subscribe me。you are %s", name);
		return ApiResult.success(message);
	}

	@MessageMapping("/hello")
	@SendTo("topic/greetings")
	public ApiResult<String> hello(String name) throws Exception {
		System.out.println("========================hello");
		String message = String.format("hello ！you have subscribe me。you are %s", name);
//		Thread.sleep(3000); // simulated delay
		return ApiResult.success(message);
	}

}
